package com.example.dialogdatepicker;

import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class DialogDatePicker extends AppCompatActivity {

    private TextView showdate;
    private Button   setdate;
    private int      year;
    private int      month;
    private int      day;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog_date_picker);

        showdate=(TextView) this.findViewById(R.id.showtime);
        setdate=(Button) this.findViewById(R.id.setdate);
        Calendar c=Calendar.getInstance(Locale.CHINA);

        year=c.get(Calendar.YEAR);
        month=c.get(Calendar.MONTH);
        day=c.get(Calendar.DAY_OF_MONTH);
        showdate.setText("当前日期："+year+"-"+(month+1)+"-"+day);


        setdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog my_datePickerDialog=new DatePickerDialog(DialogDatePicker.this,Datelistener,year,month,day);
                my_datePickerDialog.show();
            }
        });
    }

    private DatePickerDialog.OnDateSetListener Datelistener=new DatePickerDialog.OnDateSetListener()
    {

        @Override
        public void onDateSet(DatePicker v,int y,int m,int d){
            Calendar current = Calendar.getInstance(Locale.CHINA);    //获取当前时间
            Calendar date    = Calendar.getInstance();                //初始化Calendar日历对象

            //将DatePickerDialog设置的日期传入Calendar日历对象中
            date.set(Calendar.YEAR,y);
            date.set(Calendar.MONTH,m);
            date.set(Calendar.DAY_OF_MONTH,d);

           if(date.compareTo(current)<=0) {
                year = y;
                month = m;
                day = d;
                updateDate();
            }else{
                Toast.makeText(DialogDatePicker.this, "设置时间大于当前时间，请重试！", Toast.LENGTH_SHORT).show();
            }
        }

        private void updateDate()
        {
            showdate.setText("当前日期："+year+"-"+(month+1)+"-"+day);
        }
    };
}
